import socket
import struct
import threading
import time
import os
import datetime
from sensors.bottomfac.config import Config
from sensors.models import DevInfo
from sensors.common.AutoPlay import setAutoForSquirm, closeAutoForSquirm



#: tcp通讯类
class TcpSever(object):
    tcpState = False
    sendState = False
    data = b''

    #: 线程服务函数
    def _tcpProc(self, host, port):
        sever = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sever.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sever.bind((host, port))
        try:
            sever.listen(5)
        except socket.error:
            sever.close()
            self.tcpState = False

        while True:
            sock, addr = sever.accept()
            #print('new connect...', sock)
            try:
                while True:
                    if (self.sendState):
                        sock.sendall(self.data)
                        self.sendState = False
                        self.tcpState = True
                        # print('send ok...')
                    else:
                        continue
            except:
                sock.close()
                self.tcpState = False
                # print('err...')

    #: TCP初始化函数
    def tcpInit(self):
        t1 = threading.Thread(target=tcp._tcpProc, args=(Config.tcpHost, Config.tcpPort))
        t1.start()
        print('Tcp Sever run...')

    #: 下发命令: 返回值:False-失败 True-成功
    def tcpSend(self, data):
        self.data = struct.pack("%dB" % (len(data)), *data)
        self.sendState = True
        time.sleep(0.3)
        if (self.tcpState):
            return True
        else:
            return False

    def tcpSwitchOpen(self, name):
        flag = {
            '排风扇': self.tcpSend(self.Order.set_1),
            '模拟光1': self.tcpSend(self.Order.set_2),
            '模拟光2': self.tcpSend(self.Order.set_3),
            '模拟光3': self.tcpSend(self.Order.set_4),
            '模拟光4': self.tcpSend(self.Order.set_5),
            '营养液1': self.tcpSend(self.Order.set_6),
            '营养液2': self.tcpSend(self.Order.set_7),
            '营养液3': self.tcpSend(self.Order.set_8),
            '营养液4': self.tcpSend(self.Order.set_9),
            '模拟风1': self.tcpSend(self.Order.set_10),
            '模拟风2': self.tcpSend(self.Order.set_11),
            '蠕动泵': self.tcpSend(self.Order.set_12)
        }
        return flag.get(name)

    def tcpSwitchClose(self, name):
        flag = {
            '排风扇': self.tcpSend(self.Order.reset_1),
            '模拟光1': self.tcpSend(self.Order.reset_2),
            '模拟光2': self.tcpSend(self.Order.reset_3),
            '模拟光3': self.tcpSend(self.Order.reset_4),
            '模拟光4': self.tcpSend(self.Order.reset_5),
            '营养液1': self.tcpSend(self.Order.reset_6),
            '营养液2': self.tcpSend(self.Order.reset_7),
            '营养液3': self.tcpSend(self.Order.reset_8),
            '营养液4': self.tcpSend(self.Order.reset_9),
            '模拟风1': self.tcpSend(self.Order.reset_10),
            '模拟风2': self.tcpSend(self.Order.reset_11),
            '蠕动泵': self.tcpSend(self.Order.reset_12)
        }
        return flag.get(name)

    class Order(object):
        set_all = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x11, 0x8F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA2, 0x16]
        reset_all = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x11, 0x9F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                     0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x16]
        set_1 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x16]
        set_2 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x89, 0x16]
        set_3 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x82, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8A, 0x16]
        set_4 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x83, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8B, 0x16]
        set_5 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8C, 0x16]
        set_6 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x85, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8D, 0x16]
        set_7 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8E, 0x16]
        set_8 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8F, 0x16]
        set_9 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x16]
        set_10 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x89, 0x00, 0x00, 0x00, 0x00, 0x00, 0x91, 0x16]
        set_11 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x8A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x92, 0x16]
        set_12 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x8B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x93, 0x16]
        reset_1 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x98, 0x16]
        reset_2 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x91, 0x00, 0x00, 0x00, 0x00, 0x00, 0x99, 0x16]
        reset_3 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x92, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9A, 0x16]
        reset_4 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x93, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9B, 0x16]
        reset_5 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x94, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9C, 0x16]
        reset_6 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x95, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9D, 0x16]
        reset_7 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x96, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9E, 0x16]
        reset_8 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x97, 0x00, 0x00, 0x00, 0x00, 0x00, 0x9F, 0x16]
        reset_9 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x98, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA0, 0x16]
        reset_10 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x99, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA1, 0x16]
        reset_11 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x9A, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA2, 0x16]
        reset_12 = [0x55, 0x00, 0x00, 0x00, 0x00, 0xAA, 0x03, 0x06, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x00, 0xA3, 0x16]

    order = Order()


# {'Time': 'C777-67-00 46:46:46', 'Hum': 25.4, 'Temp': 25.3, 'CO2': 1002, 'Temp2': 24.9, 'PH': 4.9, 'ECAline': 1413.0, 'EC': 314.5}
#: 解析处理类
class ParseData(object):
    class Data(object):
        time = ''
        hum = 0.0
        temp = 0.0
        co2 = 0.0
        waterTemp = 0.0
        ph = 0.0
        ecAline = 0.0
        ec = 0.0
        rcvC = 0

    #: 实例化数据
    sensorDatas = Data()
    meanDatas = Data()

    #: 解析JSON
    def parseData(self, msg):
        try:
            self.sensorDatas.time = msg['Time']
            self.sensorDatas.hum = msg['Hum']
            self.sensorDatas.temp = msg['Temp']
            self.sensorDatas.co2 = msg['CO2']
            self.sensorDatas.waterTemp = msg['Temp2']
            self.sensorDatas.ph = msg['PH']
            self.sensorDatas.ecAline = msg['ECAline']
            self.sensorDatas.ec = msg['EC']

            # TODO ph
            #累加平均
            self.sensorDatas.rcvC += 1
            self.meanDatas.ph +=  self.sensorDatas.ph
            if(self.sensorDatas.rcvC >= Config.phCount and Config.sysInitState == True):
                targetDev = DevInfo.objects.get(dev_name='蠕动泵')
                ph = targetDev.other_set.split(";")[0]
                ph_low = float(ph.split("-")[0])
                ph_hei = float(ph.split("-")[1])
                '''
                ec = targetDev.other_set.split(";")[1]
                ec_low = float(ec.split("-")[0])
                ec_hei = float(ec.split("-")[1])
                '''
                ph = self.meanDatas.ph / Config.phCount         # 平均值
                if(ph >= ph_hei):   # 超过阈值
                    setAutoForSquirm()
                if(ph <= ph_low):   # 低于阈值
                    closeAutoForSquirm()
            else:
                pass
        except:
            print('parse json err ...')
            pass

    def dealCo2(self):
        pass

    def dealPh(self):
        pass

    def dealEc(self):
        pass

    def deal(self):
        pass


#: 设置/获取日期时间: 时间格式: 2021-01-20 11:33:19
class SetSysTime(object):

    #: 获取系统时间
    def getSysTime(self):
        date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print('getSysTime: ', date)
        return date

    #: 设置系统时间 返回值：系统时间
    def setSysTime(self, date):
        os.system('sudo date  --s="%s"' % date)
        time.sleep(0.1)
        return self.getSysTime()

    #: 设置自动系统时间 返回值：系统时间 (调用此方法需要设置超时时间)
    def autoGetTime(self):
        os.system('sudo service ntp start && sudo ntpd -s –d')
        time.sleep(4)
        return self.getSysTime()


#: 对模块下发控制命令，参看main函数使用方法
tcp = TcpSever()
#: 处理实时数据
parse = ParseData()
#: 设置系统时间
sysTime = SetSysTime()

'''
if __name__ == '__main__':

    #: tcp服务器初始化(只需要调用一次)
    tcp.tcpInit()
    while True:
        time.sleep(3)
        #: 使用tcpSend函数发送命令 每一个继电器有 set=开 reset=关 两种命令 一共12组
        print('set_all...', tcp.tcpSend(tcp.Order.set_1))
        print('set_all...', tcp.tcpSend(tcp.Order.set_2))
        print('set_all...', tcp.tcpSend(tcp.Order.set_3))
        print('set_all...', tcp.tcpSend(tcp.Order.set_4))
        print('set_all...', tcp.tcpSend(tcp.Order.set_5))
        print('set_all...', tcp.tcpSend(tcp.Order.set_6))
        print('set_all...', tcp.tcpSend(tcp.Order.set_7))
        print('set_all...', tcp.tcpSend(tcp.Order.set_8))
        print('set_all...', tcp.tcpSend(tcp.Order.set_9))
        print('set_all...', tcp.tcpSend(tcp.Order.set_10))
        print('set_all...', tcp.tcpSend(tcp.Order.set_11))
        print('set_all...', tcp.tcpSend(tcp.Order.set_12))
        time.sleep(3)
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_1))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_2))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_3))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_4))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_5))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_6))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_7))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_8))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_9))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_10))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_11))
        print('reset_all...', tcp.tcpSend(tcp.Order.reset_12))
'''
